package com.ruoyi.service.impl;

import com.ruoyi.entity.ActivityDetailDto;
import com.ruoyi.entity.ActivitySkuDto;
import com.ruoyi.mapper.ActivityMapper;
import com.ruoyi.mapper.ActivitySkuRelateMapper;
import com.ruoyi.mapper.ProductSkusMapper;
import com.ruoyi.product.domain.ProductActivity;
import com.ruoyi.product.domain.ProductSku;
import com.ruoyi.product.domain.VerActivitySkuRelate;
import com.ruoyi.service.ProductActivitysService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductActivityServiceImpl implements ProductActivitysService {

    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private ProductSkusMapper productSkusMapper;
    @Resource
    private ActivitySkuRelateMapper activitySkuRelateMapper;

    @Override
    @Transactional
    public boolean deleteActivityById(Long[] activityId) {
        for (Long id : activityId){
            activitySkuRelateMapper.deleteVerActivitySkuRelateById(id);
        }
        // 逻辑删除活动
        int rows = activityMapper.deleteById(activityId);
        return rows >= 0;
    }

    @Override
    @Transactional
    public Long createActivity(ProductActivity activity) {
        // 设置创建时间和更新时间
        activity.setCreateTime(new Date());
        activity.setUpdateTime(new Date());

        // 初始状态根据时间判断
        if (activity.getStatus() == null) {
            LocalDateTime nowTime = LocalDateTime.now();
            // 将Date类型转换为LocalDateTime进行比较
            LocalDateTime startTime = activity.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            LocalDateTime endTime = activity.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

            if (nowTime.isBefore(startTime)) {
                activity.setStatus(0); // 未开始
            } else if (nowTime.isAfter(endTime)) {
                activity.setStatus(2); // 已结束
            } else {
                activity.setStatus(1); // 进行中
            }
        }

        activityMapper.insert(activity);
        return activity.getActivityId();
    }

    @Override
    @Transactional
    public boolean updateActivity(ProductActivity activity) {
        activity.setUpdateTime(new Date());
        int rows = activityMapper.update(activity);
        return rows > 0;
    }

    @Override
    public ActivityDetailDto getActivityDetail(Long activityId) {
        ProductActivity activity = activityMapper.selectById(activityId);
        if (activity == null) {
            return null;
        }

        ActivityDetailDto detailDTO = new ActivityDetailDto();
        BeanUtils.copyProperties(activity, detailDTO);

        // 查询活动关联的商品
        List<VerActivitySkuRelate> relates = activitySkuRelateMapper.selectByActivityId(activityId);
        if (relates != null && !relates.isEmpty()) {
            List<Long> skuIds = relates.stream()
                    .map(VerActivitySkuRelate::getSkuId)
                    .collect(Collectors.toList());

            List<ProductSku> skus = productSkusMapper.selectByIds(skuIds);
            if (skus != null && !skus.isEmpty()) {
                List<ActivitySkuDto> skuDTOList = new ArrayList<>();
                for (ProductSku sku : skus) {
                    ActivitySkuDto skuDTO = new ActivitySkuDto();
                    BeanUtils.copyProperties(sku, skuDTO);

                    // 设置活动价格
                    for (VerActivitySkuRelate relate : relates) {
                        if (relate.getSkuId().equals(sku.getId())) {
                            skuDTO.setActivityPrice(relate.getPrice());
                            skuDTO.setActivityId(activityId);
                            break;
                        }
                    }
                    skuDTOList.add(skuDTO);
                }
                detailDTO.setSkuList(skuDTOList);
            }
        }

        return detailDTO;
    }

    @Override
    public List<ProductActivity> getAllActivities(ProductActivity  activity) {
        List<ProductActivity> activities = activityMapper.selectAll(activity);

        // 实时更新活动状态
        Date now = new Date();
        for (ProductActivity act : activities) {
            Integer oldStatus = act.getStatus();
            if (now.before(act.getStartTime())) {
                act.setStatus(0); // 未开始
            } else if (now.after(act.getEndTime())) {
                act.setStatus(2); // 已结束
            } else {
                act.setStatus(1); // 进行中
            }

            // 如果状态发生变化，则更新数据库
            if (oldStatus == null || !oldStatus.equals(act.getStatus())) {
                act.setUpdateTime(now);
                activityMapper.update(act);
            }
        }

        return activities;
    }

    @Override
    @Transactional
    public boolean addSkuToActivity(Long activityId, Long skuId, BigDecimal price) {
        // 检查活动是否存在
        ProductActivity activity = activityMapper.selectById(activityId);
        if (activity == null) {
            return false;
        }

        // 检查商品是否存在
        ProductSku sku = productSkusMapper.selectById(skuId);
        if (sku == null) {
            return false;
        }

        // 检查是否已关联
        VerActivitySkuRelate existing = activitySkuRelateMapper.selectByActivityAndSku(activityId, skuId);
        if (existing != null && existing.getIsDelete() == 0) {
            // 已存在，更新价格
            return activitySkuRelateMapper.updatePrice(activityId, skuId, price) > 0;
        }

        // 新增关联
        VerActivitySkuRelate relate = new VerActivitySkuRelate();
        relate.setActivityId(activityId);
        relate.setSkuId(skuId);
        relate.setPrice(price);
        relate.setIsDelete(0);
        LocalDateTime now = LocalDateTime.now();
        relate.setCreateTime(now);
        relate.setUpdateTime(now);

        return activitySkuRelateMapper.insert(relate) > 0;
    }

    @Override
    @Transactional
    public boolean removeSkuFromActivity(Long activityId, Long skuId) {
        return activitySkuRelateMapper.delete(activityId, skuId) > 0;
    }

    @Override
    @Transactional
    public boolean updateActivitySkuPrice(Long activityId, Long skuId, BigDecimal price) {
        return activitySkuRelateMapper.updatePrice(activityId, skuId, price) > 0;
    }

    @Override
    public List<VerActivitySkuRelate> getSkusByActivityId(Long activityId) {
        return activitySkuRelateMapper.selectByActivityId(activityId);
    }
}
